﻿using AutoMapper;
using ManagementApi.Authorizers;
using ManagementApi.Models;
using ManagementApi.Models.Manage.ProjectCorp;
using ManagementApi.Mvc;
using ManagementApi.Mvc.ApplicationContexts;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Modules.Constructor;
using Modules.Corp;
using Modules.Project;
using Modules.Project.Entitys;
using PmSoft.Entity;
using PmSoft.Utilities;

namespace ManagementApi.Controllers.CorpPannel
{
    /// <summary>
    /// 项目管理员-参建单位管理接口
    /// </summary>
    [Route("/api/v1/corp/projectcorp")]
    [ApiController]
    [Authorize(Roles = "Corp")]
    public class ProjectCorpController : ControllerBase
    {
        private readonly ProjectCorpService projectCorpService;
        private readonly ProjectGroupMemberService projectGroupMemberService;
        private readonly CorpApplicationContext applicationContext;
        private readonly IMapper mapper;
        private readonly ProjectOwnAuthorizer ownAuthorizer;
        private readonly CorpService corpService;

        public ProjectCorpController(ProjectCorpService projectCorpService,
            IMapper mapper,
            ProjectGroupMemberService projectGroupMemberService,
            CorpApplicationContext applicationContext,
            ProjectOwnAuthorizer ownAuthorizer,
            CorpService corpService
            )
        {
            this.projectCorpService = projectCorpService;
            this.mapper = mapper;
            this.projectGroupMemberService = projectGroupMemberService;
            this.applicationContext = applicationContext;
            this.ownAuthorizer = ownAuthorizer;
            this.corpService = corpService;
        }

        /// <summary>
        /// 查询未参与当前项目的企业
        /// </summary>
        /// <returns></returns>
        //[HttpGet("corps_pulldown")]
        //public ApiResult<IEnumerable<CorpInfo>> GetCorpsPulldown()
        //{
        //    var projectCoprs = projectCorpService.GetProjectCorpsByProjectId(applicationContext.CurrentProjectInfo.ProjectId).Where(i => i.Role != 项目参建单位类型.建设单位);
        //    return ApiResult<IEnumerable<CorpInfo>>.Success(corpService.GetCorpInfosNotCorpIds(projectCoprs.Select(i => i.CorpId)));
        //}

        /// <summary>
        /// author:hzj date:2023/12/08 describe:新增参建单位（不存在需要创建建设单位的情况）
        /// </summary>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost("create")]
        public ApiResult CreateProjectCorp(ProjectCorpEditForm form)
        {
            form.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            List<ProjectCorp> projectCorps = projectCorpService.GetProjectCorpsByProjectId(form.ProjectId ?? 0).Where(i => i.Role == form.Role).ToList();

            if (projectCorps.Exists(i => i.Role == 项目参建单位类型.监理)) return ApiResult.Failure("监理已存在");
            ProjectCorp entity = new();
            mapper.Map(form, entity);
            Modules.Corp.CorpInfo corpInfo = new Modules.Corp.CorpInfo();
            if (form.CorpId.HasValue)
            {
                mapper.Map(form, corpInfo);
                corpInfo.Name = form.CorpName ?? string.Empty;
                corpInfo.HasAuth = false;
                corpInfo.Code = form.CorpCode ?? string.Empty;
                corpInfo.Legalman = form.LegalMan ?? string.Empty;
                corpInfo.DataSource = DataSource.手动新增;
                if (form.CorpId.HasValue)
                {
                    corpInfo.CorpId = form.CorpId.Value;
                }
            }
            projectCorpService.CreateProjectCorp(entity, form.CorpId.HasValue && form.CorpId.Value > 0 ? null : corpInfo, form.Attachments ?? new List<string>());
            return ApiResult.Success("创建成功");
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:编辑参建单位（不存在需要创建建设单位的情况）
        /// </summary>
        /// <param name="id"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPut("update/{id}")]
        public ApiResult UpdateProjectCorp(int id, ProjectCorpEditForm form)
        {
            form.ProjectId = applicationContext.CurrentProjectInfo.ProjectId;
            List<ProjectCorp> projectCorps = projectCorpService.GetProjectCorpsByProjectId(form.ProjectId ?? 0).Where(i => i.Role == form.Role && i.Id != id).ToList();

            if (projectCorps.Exists(i => i.Role == 项目参建单位类型.监理)) return ApiResult.Failure("监理已存在");
            ProjectCorp? data = projectCorpService.GetProjectCorp(id);
            if (data == null) return ApiResult.Failure("参建单位不存在");

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(data.ProjectId);

            #endregion 验证数据权限

            if (data.CorpId != form.CorpId) return ApiResult.Failure("参建单位不允许修改企业信息");
            mapper.Map(form, data);
            Modules.Corp.CorpInfo corpInfo = new Modules.Corp.CorpInfo();
            if (form.CorpId.HasValue)
            {
                mapper.Map(form, corpInfo);
                corpInfo.Code = form.CorpCode ?? string.Empty;
                corpInfo.Legalman = form.LegalMan ?? string.Empty;
            }
            projectCorpService.UpdateProjectCorp(data, form.CorpId.HasValue ? null : corpInfo, form.Attachments ?? new List<string>());
            return ApiResult.Success("修改成功");
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:参建单位表单数据
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        [HttpGet("{id}/form")]
        public ApiResult<ProjectCorpEditForm> GetProjectCorp(int id)
        {
            ProjectCorp? data = projectCorpService.GetProjectCorp(id);
            if (data == null)
                return ApiResult<ProjectCorpEditForm>.Failure("参建单位不存在");
            return ApiResult<ProjectCorpEditForm>.Success(data.AsProjectCorpFrom());
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:获取参建单位列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("page")]
        public ApiResult<IEnumerable<ProjectCorpDto>> GetProjectCorps()
        {
            var projectInfo = applicationContext.CurrentProjectInfo;
            var projectCorps = projectCorpService.GetProjectCorpsByProjectId(projectInfo.ProjectId);//非总包的参建企业
            var dtos = projectCorps.Select(m => m.AsDto(projectInfo, applicationContext)).ToList();
            var lumpContractor = corpService.GetCorpInfo(projectInfo.LumpContractorCorpId);//总包
            if (lumpContractor != null)
            {
                var projectCorpDto = lumpContractor.AsDto(projectInfo, applicationContext, "总承包");
                dtos.Add(projectCorpDto);
            }
            var buildConstructor = applicationContext.GetService<ConstructorService>().GetConstructorInfo(projectInfo.BuildCorpId);//建设单位
            if (buildConstructor != null)
            {
                var projectCorpDto = buildConstructor.AsDto(projectInfo, applicationContext);
                dtos.Add(projectCorpDto);
            }

            return ApiResult<IEnumerable<ProjectCorpDto>>.Success(dtos);
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:删除参建单位
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        public ApiResult Delete(string ids)
        {
            var datas = projectCorpService.GetProjectCorps(ValueUtility.ConvertToList<int>(ids));

            #region 验证数据权限

            ownAuthorizer.CheckAndThrowIfOwnAuthenticationFailed(datas.Select(i => i.ProjectId));

            #endregion 验证数据权限

            projectCorpService.DeletedProjectCorps(ValueUtility.ConvertToList<int>(ids));
            return ApiResult.Success("删除成功");
        }

        /// <summary>
        /// author:hzj date:2023/12/08 describe:企业下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("pulldown")]
        public ApiResult<IEnumerable<ProjectCorpDto>> GetPulldown()
        {
            var projectInfo = applicationContext.CurrentProjectInfo;
            var projectCorps = projectCorpService.GetProjectCorpsByProjectId(projectInfo.ProjectId);
            var projectCorpDtos = projectCorps.Select(source => source.AsDto(projectInfo, applicationContext)).ToList();
            var lumpContractor = corpService.GetCorpInfo(projectInfo.LumpContractorCorpId);//总包
            if (lumpContractor != null)
            {
                var projectCorpDto = lumpContractor.AsDto(projectInfo, applicationContext, "总承包");
                projectCorpDtos.Add(projectCorpDto);
            }
            return ApiResult<IEnumerable<ProjectCorpDto>>.Success(projectCorpDtos);
        }
    }
}